package com.example.operation.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.operation.system.dao.UserInfoMapper;
import com.example.operation.system.entity.UserInfo;
import com.example.operation.system.service.UserInfoService;
import com.example.operation.system.util.Md5Util;
import com.example.substation.common.FrameException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    public final static FrameException FRAME_EXCEPTION_SYSTEM_EXCEPTION = new FrameException().setCode(50000)
            .setMessage("系统异常·");
    public final static FrameException FRAME_EXCEPTION_WRONG_PASSWORD = new FrameException().setCode(50001)
            .setMessage("您输入的帐号或密码不正确，请重新输入。");

    /**
     * 登陆
     *
     * @param userInfo
     * @return
     */
    @Override
    public boolean login(UserInfo userInfo, HttpServletRequest request) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getLoginName, userInfo.getLoginName());
        UserInfo user = baseMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new FrameException(FRAME_EXCEPTION_WRONG_PASSWORD);
        }
        String password = Md5Util.encryptMd5(userInfo.getPassword());
        if (Objects.equals(password, user.getPassword())) {
            return true;
        } else {
            throw new FrameException(FRAME_EXCEPTION_WRONG_PASSWORD);
        }
    }

    /**
     * 插入用户表
     * @param userInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(UserInfo userInfo) {
        String password = Md5Util.encryptMd5(userInfo.getPassword());
        userInfo.setPassword(password);
        return baseMapper.insert(userInfo) > 0;
    }
    /**
     * 修改用户表
     * @param userInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(UserInfo userInfo) {
        String password = Md5Util.encryptMd5(userInfo.getPassword());
        userInfo.setPassword(password);
        return baseMapper.updateById(userInfo) > 0;
    }

    /**
     * 分页查询
     * @param userInfo
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage<UserInfo> paging(UserInfo userInfo, int page, int limit) {
        return baseMapper.selectPage(new Page<>(page, limit), new QueryWrapper<>(userInfo));
    }
}
